package cloud.lysky.java.on.concurrent.lock.reentrantlock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author luoly
 * @describe
 * @date 2023/3/15 19:14
 **/
// 模拟抢票场景
public class ReentrantLockDemo {
    // 默认非公平
    private final ReentrantLock lock = new ReentrantLock();
    //总票数
    private static int tickets = 8;

    //够买票
    public void purchase() {
        //首先获得锁，可以理解为买票过程中轮到你站在柜台面前
        lock.lock();
        //使用try-finally语句保证锁会被释放
        try{
            if (tickets > 0){
                //如果还有票
                //休眠20ms,模拟购票需要的时间
                Thread.sleep(30);
                System.out.println(Thread.currentThread().getName() + "购买了第" + tickets-- + "张票");
            }else{
                System.out.println("票已经卖完了," + Thread.currentThread().getName() + "抢票失败");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo ticketSystem = new ReentrantLockDemo();
        for (int i = 1; i <= 10; i++) {
            //抢票
            Thread thread = new Thread(ticketSystem::purchase, "线程" + i);
            thread.start();
        }
        try{
            Thread.sleep(3000);
        }catch ( InterruptedException e) {
            System.err.println("Occur error");
        }
        System.out.println("剩余票数: " + tickets);
    }
}
